// Get the x/y offsets of a given node in a web page, accounting for (non)static
// positioning, scroll positions, table and body node special behaviour and the
// in-page position of surrounding iframe elements, when singleFrame === false.
//
// (Code adapted 2008-03 from Firebug by Joe Hewitt, under the MIT license.)
function getViewOffset(node, singleFrame) {
  function addOffset(node, coords, view) {
    var p = node.offsetParent;
    coords.x += node.offsetLeft - (p ? p.scrollLeft : 0);
    coords.y += node.offsetTop - (p ? p.scrollTop : 0);

    if (p) {
      if (p.nodeType == 1) {
        var parentStyle = view.getComputedStyle(p, '');
        if (parentStyle.position != 'static') {
          coords.x += parseInt(parentStyle.borderLeftWidth);
          coords.y += parseInt(parentStyle.borderTopWidth);

          if (p.localName == 'TABLE') {
            coords.x += parseInt(parentStyle.paddingLeft);
            coords.y += parseInt(parentStyle.paddingTop);
          }
          else if (p.localName == 'BODY') {
            var style = view.getComputedStyle(node, '');
            coords.x += parseInt(style.marginLeft);
            coords.y += parseInt(style.marginTop);
          }
        }
        else if (p.localName == 'BODY') {
          coords.x += parseInt(parentStyle.borderLeftWidth);
          coords.y += parseInt(parentStyle.borderTopWidth);
        }

        var parent = node.parentNode;
        while (p != parent) {
          coords.x -= parent.scrollLeft;
          coords.y -= parent.scrollTop;
          parent = parent.parentNode;
        }
        addOffset(p, coords, view);
      }
    }
    else {
      if (node.localName == 'BODY') {
        var style = view.getComputedStyle(node, '');
        coords.x += parseInt(style.borderLeftWidth);
        coords.y += parseInt(style.borderTopWidth);

        var htmlStyle = view.getComputedStyle(node.parentNode, '');
        coords.x -= parseInt(htmlStyle.paddingLeft);
        coords.y -= parseInt(htmlStyle.paddingTop);
      }

      if (node.scrollLeft)
        coords.x += node.scrollLeft;
      if (node.scrollTop)
        coords.y += node.scrollTop;

      var win = node.ownerDocument.defaultView;
      if (win && (!singleFrame && win.frameElement))
        addOffset(win.frameElement, coords, win);
    }
  }

  var coords = { x: 0, y: 0 };
  if (node)
    addOffset(node, coords, node.ownerDocument.defaultView);

  return coords;
}
